<?php
namespace App\Services\Awards;

use App\Http\Controllers\Excel\ExcelImport;
use App\Models\DecSubject;
use App\Models\Files;
use App\Models\Teaching\TeachingSubject;
use Illuminate\Support\Facades\DB;
use App\Models\System\User;
use App\Models\System\Term;
use App\Models\System\Tasks;
use App\Models\ActivityInfo;
use App\Models\Teachers;
use App\Models\DictionaryItem;
use App\Models\EventStatistics;
use App\Models\Participant;
use App\Models\FormInstance;
use Illuminate\Support\Facades\Auth;
use App\Models\System\Group;
use App\Models\File;
use App\Models\SystemTask;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Support\Facades\Log;
use Maatwebsite\Excel\Facades\Excel;
use App\Http\Controllers\Excel\ExcelExport;

class AwardsService{

    /** @var \App\Repositories\System\ActivityRepository $activityRepository */
    private $activityRepository;

    public function __construct()
    {
        $this->activityRepository = app('activityRepository');
    }

    /**
     * 获取列表
     * @author lxy
     * @datetime 2023-02-14
     */
    public function getAwardsList($request)
    {
        $jsonSearch = [];
        $limit = $request['limit'] ?? 10;
        $where = [];
        $user = Auth::user();
        $user_id = auth()->user()->id;

        !empty($request['search']['data_version_id'])   && $where[] = ['activity_info.data_version_id','=',$request['search']['data_version_id']];
        !empty($request['search']['name'])     && $where[] = ['activity_info.name','like','%'.$request['search']['name'].'%'];
        !empty($request['search']['nickname'])     && $where[] = ['d.nickname','like','%'.$request['search']['nickname'].'%'];
        !empty($request['search']['status'])     && $where[] = ['b.status','=',$request['search']['status']];
        $level = !empty($request['search']['level'])?$request['search']['level']:'';
        $category = !empty($request['search']['category'])?$request['search']['category']:'';
        if (isset($request['search']['grade'] )&& !empty($request['search']['grade'])){
            $jsonSearch['grade'] = $request['search']['grade'];
        }
        if (isset($request['search']['class_item'] )&& !empty($request['search']['class_item'])){
            $jsonSearch['class_item'] = $request['search']['class_item'];
        }
        //非审核权限只能看到自己提交的数据
//        if(!is_check(178)){
//            $where[] = ['activity_info.creator_id','=',$user_id];
//        }
        $where[] = ['activity_info.deleted','=',0];
        if(!empty($request['honor'])){
            $request['form_key'] = 'TEACHER_HONOR_TABLE';
            $where[] = ['activity_info.activity_category', '=', 'TEACHER_HONOR_TABLE'];//班级荣誉
        }else {
            $request['form_key'] = 'TEACHER_AWARD_TABLE';
            $where[] = ['activity_info.activity_category', '=', 'TEACHER_AWARD_TABLE'];//获奖情况
        }
        $result = ActivityInfo::select('b.data_version_name','activity_info.id','activity_info.name','activity_info.is_push','activity_info.begin_date','activity_info.end_date','activity_info.created_at','activity_info.level','activity_info.grade','activity_info.class_item','activity_info.category','activity_info.proof_material','b.status','c.participant','d.nickname','activity_info.creator_id')
                ->leftJoin('form_instance as b' ,'activity_info.form_instance_id','=','b.id')
                ->leftJoin('event_statistics as c','c.activity_info_id','=','activity_info.id')
                ->leftJoin('users as d','activity_info.creator_id','=','d.id')
            ->leftJoin('participant as p', 'activity_info.id', '=', 'p.activity_info_id')
                ->when(!empty($jsonSearch), function($q) use($jsonSearch) {
                    foreach($jsonSearch as $k => $id) {
                        $q->whereRaw(" JSON_EXTRACT(activity_info.`".$k."`,'$[0].optionId') = $id");
                    }
                })
                ->where($where)
                ->manageable()
                ->when(isset($request['user_id']) && !empty($request['user_id']), function($q) use($request){//处理档案袋只查看自己的数据
                    $q->where('b.status', '=', 'PASS');
                    $q->where('activity_info.creator_id', $request['user_id'])->orWhere(function($query) use($request) {
                        $query->whereHas('participants', function($qqy) use($request){
                            $qqy->where('user_id', $request['user_id']);
                            $qqy->where('activity_category', $request['form_key']);
                            $qqy->where('b.status', '=', 'PASS');
                        });
                    });
                })
                ->when($level,function($q) use($level){
                    $str = '';
                    switch($level){
                        case '106':
                            $str = " ( JSON_CONTAINS(`activity_info`.level,JSON_OBJECT('optionId', 106)) or JSON_CONTAINS(`activity_info`.level,JSON_OBJECT('optionId', 151)) ) ";break;
                        case '107':
                            $str = " ( JSON_CONTAINS(`activity_info`.level,JSON_OBJECT('optionId', 107)) or JSON_CONTAINS(`activity_info`.level,JSON_OBJECT('optionId', 191)) ) ";break;
                        case '108':
                            $str = " ( JSON_CONTAINS(`activity_info`.level,JSON_OBJECT('optionId', 108)) or JSON_CONTAINS(`activity_info`.level,JSON_OBJECT('optionId', 192)) ) ";break;
                        case '109':
                            $str = " ( JSON_CONTAINS(`activity_info`.level,JSON_OBJECT('optionId', 109)) or JSON_CONTAINS(`activity_info`.level,JSON_OBJECT('optionId', 194)) ) ";break;
                        case '110':
                            $str = " ( JSON_CONTAINS(`activity_info`.level,JSON_OBJECT('optionId', 110)) or JSON_CONTAINS(`activity_info`.level,JSON_OBJECT('optionId', 195)) ) ";break;
                        case '111':
                            $str = " ( JSON_CONTAINS(`activity_info`.level,JSON_OBJECT('optionId', 111)) or JSON_CONTAINS(`activity_info`.level,JSON_OBJECT('optionId', 196)) ) ";break;
                        case '112':
                            $str = " ( JSON_CONTAINS(`activity_info`.level,JSON_OBJECT('optionId', 112)) or JSON_CONTAINS(`activity_info`.level,JSON_OBJECT('optionId', 197)) ) ";break;
                        case '113':
                            $str = " ( JSON_CONTAINS(`activity_info`.level,JSON_OBJECT('optionId', 113)) or JSON_CONTAINS(`activity_info`.level,JSON_OBJECT('optionId', 198)) ) ";break;
                    }
                    return $q->whereRaw($str);
                })
                ->when($category,function($q) use($category){
                    return $q->whereRaw(" JSON_EXTRACT(activity_info.`category`,'$[0].optionId') = $category");
                })
            /**
                ->when($grade,function($q) use($grade){
                    return $q->whereRaw(" JSON_EXTRACT(activity_info.`grade`,'$[0].optionId') = $grade");
                })**/
                ->when(!empty($request['search']['materials_date']),function($q) use($request){
                    return $q->whereRaw(" activity_info.data_version_id in ({$request['search']['materials_date']})");
                })
                ->when(!empty($request['search']['whereStr']),function($q) use($request){
                    return $q->whereRaw($request['search']['whereStr']);
                })
                ->with(['participant', 'creator'])
                ->orderBy('activity_info.created_at','desc')
                ->groupBy('activity_info.id')
                ->paginate($limit)
                ->toArray();
        $dics = [];
        $dic = DictionaryItem::select('code','item_order as order','id as optionId','parent_id as parentId','item_value as selectKey','item_name as selectValue')->whereIn('code',['grade','classItem'])->where('deleted',0)->orderBy('item_order')->get()->toArray();
        foreach($dic as $k=>$v){
            $dics[$v['code']][$v['optionId']] = $v;
        }
        //echo json_encode($dics);exit();
        foreach($result['data'] as $k=>&$v){
            if(!empty($v['category_array']) && $v['category_array'][0]['optionId']==150){
                $v['category_array'][0]['selectValue'] = '各类指导奖（学生）';
            }
            $v['grade_name'] = $dics['GRADE'][$v['grade']]['selectValue'] ?? '';
            $v['class_name'] = $dics['classItem'][$v['class_item']]['selectValue'] ?? '';

            if($user->id == $v['creator_id']) {
                $v['is_createor'] = 1;
            }else{
                $v['is_createor'] = 0;
            }
            $v['is_part'] = 0;
            if(!empty($v['participant'])) {
                $participant = array_column($v['participant'], 'user_id');
                if (in_array($user->id, $participant) && $v['is_createor'] != 1) {
                    $v['is_part'] = 1;
                }
            }
        }

        $result['limit'] = $limit;

        return $result;
    }

    /**
     * 导出
     * @author lxy
     * @datetime 2023-02-24
     */
    public function exportAwards($request)
    {
        $where = [];

        $user_id = auth()->user()->id;

        !empty($request['search']['data_version_id'])   && $where[] = ['activity_info.data_version_id','=',$request['search']['data_version_id']];
        !empty($request['search']['name'])     && $where[] = ['activity_info.name','like','%'.$request['search']['name'].'%'];
        !empty($request['search']['nickname'])     && $where[] = ['d.nickname','like','%'.$request['search']['nickname'].'%'];
        if(!empty($request['search']['status'])){
            $where[] = ['b.status','=',$request['search']['status']];
        }else{
            $where[] = ['b.status','=','PASS'];
        }
        $level = !empty($request['search']['level'])?$request['search']['level']:'';
        $category = !empty($request['search']['category'])?$request['search']['category']:'';
        $grade = !empty($request['search']['grade'])?$request['search']['grade']:'';

        //非审核权限只能看到自己提交的数据
        if(!is_check(178)){
            $where[] = ['activity_info.creator_id','=',$user_id];
        }
        $where[] = ['activity_info.deleted','=',0];

        $where[] = ['activity_info.activity_category','=','TEACHER_AWARD_TABLE'];

        $result = ActivityInfo::select('b.data_version_name','activity_info.id','activity_info.name','activity_info.begin_date','activity_info.end_date','activity_info.level','activity_info.grade','activity_info.category','b.status','c.participant','d.nickname')
                ->leftJoin('form_instance as b' ,'activity_info.form_instance_id','=','b.id')
                ->leftJoin('event_statistics as c','c.activity_info_id','=','activity_info.id')
                ->leftJoin('users as d','activity_info.creator_id','=','d.id')
                ->where($where)
                ->when($level,function($q) use($level){
                    $str = '';
                    switch($level){
                        case '106':
                            $str = " ( JSON_CONTAINS(`activity_info`.level,JSON_OBJECT('optionId', 106)) or JSON_CONTAINS(`activity_info`.level,JSON_OBJECT('optionId', 151)) ) ";break;
                        case '107':
                            $str = " ( JSON_CONTAINS(`activity_info`.level,JSON_OBJECT('optionId', 107)) or JSON_CONTAINS(`activity_info`.level,JSON_OBJECT('optionId', 191)) ) ";break;
                        case '108':
                            $str = " ( JSON_CONTAINS(`activity_info`.level,JSON_OBJECT('optionId', 108)) or JSON_CONTAINS(`activity_info`.level,JSON_OBJECT('optionId', 192)) ) ";break;
                        case '109':
                            $str = " ( JSON_CONTAINS(`activity_info`.level,JSON_OBJECT('optionId', 109)) or JSON_CONTAINS(`activity_info`.level,JSON_OBJECT('optionId', 194)) ) ";break;
                        case '110':
                            $str = " ( JSON_CONTAINS(`activity_info`.level,JSON_OBJECT('optionId', 110)) or JSON_CONTAINS(`activity_info`.level,JSON_OBJECT('optionId', 195)) ) ";break;
                        case '111':
                            $str = " ( JSON_CONTAINS(`activity_info`.level,JSON_OBJECT('optionId', 111)) or JSON_CONTAINS(`activity_info`.level,JSON_OBJECT('optionId', 196)) ) ";break;
                        case '112':
                            $str = " ( JSON_CONTAINS(`activity_info`.level,JSON_OBJECT('optionId', 112)) or JSON_CONTAINS(`activity_info`.level,JSON_OBJECT('optionId', 197)) ) ";break;
                        case '113':
                            $str = " ( JSON_CONTAINS(`activity_info`.level,JSON_OBJECT('optionId', 113)) or JSON_CONTAINS(`activity_info`.level,JSON_OBJECT('optionId', 198)) ) ";break;
                    }
                    return $q->whereRaw($str);
                })
                ->when($category,function($q) use($category){
                    return $q->whereRaw(" JSON_EXTRACT(activity_info.`category`,'$[0].optionId') = $category");
                })
                ->when($grade,function($q) use($grade){
                    return $q->whereRaw(" JSON_EXTRACT(activity_info.`grade`,'$[0].optionId') = $grade");
                })
                ->when(!empty($request['search']['materials_date']),function($q) use($request){
                    return $q->whereRaw(" activity_info.data_version_id in ({$request['search']['materials_date']})");
                })
                ->orderBy('activity_info.created_at','desc')
                ->get()
                ->toArray();

        $field_name = ['学年学期','类型','名称','开始日期','结束日期','级别','等级','创建人','状态'];
        $data = [];
        foreach($result as $k=>$v){
            $data[$k][] = $v['data_version_name'] === null?'':$v['data_version_name'];
            $data[$k][] = !empty($v['category_array'])?($v['category_array'][0]['optionId']==150?'各类指导奖（学生）':$v['category_array'][0]['selectValue']):'';
            $data[$k][] = $v['name'];
            $data[$k][] = $v['begin_date'];
            $data[$k][] = $v['end_date'];
            $data[$k][] = !empty($v['level_array'])?$v['level_array'][0]['selectValue']:'';
            $data[$k][] = !empty($v['grade_array'])?$v['grade_array'][0]['selectValue']:'';
            $data[$k][] = $v['nickname'];
            $status = '';
            if($v['status'] == 'FILL_IN'){
                $status = '未提交';
            }else if($v['status'] == 'REVIEW'){
                $status = '待审核';
            }else if($v['status'] == 'REVIEW_FAIL'){
                $status = '已驳回';
            }else if($v['status'] == 'PASS'){
                $status = '审核通过';
            }
            $data[$k][] = $status;
        }
        array_unshift($data,$field_name);

        $file_name = md5(auth()->user()->id.time()).'.xlsx';
        Excel::store(new ExcelExport($data), $file_name, 'excel');
        return [
            'file_name' => $file_name,
        ];
    }


    public function exportHonor($request)
    {
        $where = [];

        $user_id = auth()->user()->id;

        !empty($request['search']['data_version_id'])   && $where[] = ['activity_info.data_version_id','=',$request['search']['data_version_id']];
        !empty($request['search']['name'])     && $where[] = ['activity_info.name','like','%'.$request['search']['name'].'%'];
        !empty($request['search']['nickname'])     && $where[] = ['d.nickname','like','%'.$request['search']['nickname'].'%'];
        if(!empty($request['search']['status'])){
            $where[] = ['b.status','=',$request['search']['status']];
        }else{
            $where[] = ['b.status','=','PASS'];
        }
        $level = !empty($request['search']['level'])?$request['search']['level']:'';
        $category = !empty($request['search']['category'])?$request['search']['category']:'';
        $grade = !empty($request['search']['grade'])?$request['search']['grade']:'';

        //非审核权限只能看到自己提交的数据
        if(!is_check(178)){
            $where[] = ['activity_info.creator_id','=',$user_id];
        }
        $where[] = ['activity_info.deleted','=',0];
        $where[] = ['activity_info.activity_category', '=', 'TEACHER_HONOR_TABLE'];
        $result = ActivityInfo::select('b.data_version_name','activity_info.id','activity_info.name','activity_info.begin_date','activity_info.end_date','activity_info.class_item','activity_info.level','activity_info.grade','activity_info.created_at','activity_info.category','b.status','c.participant','d.nickname')
            ->leftJoin('form_instance as b' ,'activity_info.form_instance_id','=','b.id')
            ->leftJoin('event_statistics as c','c.activity_info_id','=','activity_info.id')
            ->leftJoin('users as d','activity_info.creator_id','=','d.id')
            ->where($where)
            ->when($level,function($q) use($level){
                $str = '';
                switch($level){
                    case '106':
                        $str = " ( JSON_CONTAINS(`activity_info`.level,JSON_OBJECT('optionId', 106)) or JSON_CONTAINS(`activity_info`.level,JSON_OBJECT('optionId', 151)) ) ";break;
                    case '107':
                        $str = " ( JSON_CONTAINS(`activity_info`.level,JSON_OBJECT('optionId', 107)) or JSON_CONTAINS(`activity_info`.level,JSON_OBJECT('optionId', 191)) ) ";break;
                    case '108':
                        $str = " ( JSON_CONTAINS(`activity_info`.level,JSON_OBJECT('optionId', 108)) or JSON_CONTAINS(`activity_info`.level,JSON_OBJECT('optionId', 192)) ) ";break;
                    case '109':
                        $str = " ( JSON_CONTAINS(`activity_info`.level,JSON_OBJECT('optionId', 109)) or JSON_CONTAINS(`activity_info`.level,JSON_OBJECT('optionId', 194)) ) ";break;
                    case '110':
                        $str = " ( JSON_CONTAINS(`activity_info`.level,JSON_OBJECT('optionId', 110)) or JSON_CONTAINS(`activity_info`.level,JSON_OBJECT('optionId', 195)) ) ";break;
                    case '111':
                        $str = " ( JSON_CONTAINS(`activity_info`.level,JSON_OBJECT('optionId', 111)) or JSON_CONTAINS(`activity_info`.level,JSON_OBJECT('optionId', 196)) ) ";break;
                    case '112':
                        $str = " ( JSON_CONTAINS(`activity_info`.level,JSON_OBJECT('optionId', 112)) or JSON_CONTAINS(`activity_info`.level,JSON_OBJECT('optionId', 197)) ) ";break;
                    case '113':
                        $str = " ( JSON_CONTAINS(`activity_info`.level,JSON_OBJECT('optionId', 113)) or JSON_CONTAINS(`activity_info`.level,JSON_OBJECT('optionId', 198)) ) ";break;
                }
                return $q->whereRaw($str);
            })
            ->when($category,function($q) use($category){
                return $q->whereRaw(" JSON_EXTRACT(activity_info.`category`,'$[0].optionId') = $category");
            })
            ->when($grade,function($q) use($grade){
                return $q->whereRaw(" JSON_EXTRACT(activity_info.`grade`,'$[0].optionId') = $grade");
            })
            ->when(!empty($request['search']['materials_date']),function($q) use($request){
                return $q->whereRaw(" activity_info.data_version_id in ({$request['search']['materials_date']})");
            })
            ->orderBy('activity_info.created_at','desc')
            ->get()
            ->toArray();

        $field_name = ['学年学期','名称','年级班级','级别','状态','创建人','创建日期'];
        $data = [];
        $dics = [];
        $dic = DictionaryItem::select('code','item_order as order','id as optionId','parent_id as parentId','item_value as selectKey','item_name as selectValue')->whereIn('code',['grade','classItem'])->where('deleted',0)->orderBy('item_order')->get()->toArray();
        foreach($dic as $k=>$v){
            $dics[$v['code']][$v['optionId']] = $v;
        }
        foreach($result as $k=>$v){
            $v['grade_name'] = $dics['GRADE'][$v['grade']]['selectValue'] ?? '';
            $v['class_name'] = $dics['classItem'][$v['class_item']]['selectValue'] ?? '';
            $data[$k][] = $v['data_version_name'] === null?'':$v['data_version_name'];
            $data[$k][] = $v['name'];
            $data[$k][] = $v['grade_name'].$v['class_name'];
            $data[$k][] = !empty($v['level_array'])?$v['level_array'][0]['selectValue']:'';
            $status = '';
            if($v['status'] == 'FILL_IN'){
                $status = '未提交';
            }else if($v['status'] == 'REVIEW'){
                $status = '待审核';
            }else if($v['status'] == 'REVIEW_FAIL'){
                $status = '已驳回';
            }else if($v['status'] == 'PASS'){
                $status = '审核通过';
            }
            $data[$k][] = $status;
            $data[$k][] = $v['nickname'];
            $data[$k][] = $v['created_at'];
        }
        array_unshift($data,$field_name);

        $file_name = md5(auth()->user()->id.time()).'.xlsx';
        Excel::store(new ExcelExport($data), $file_name, 'excel');
        return [
            'file_name' => $file_name,
        ];
    }
    /**
     * 获取参与人
     * @author lxy
     * @datetime 2023-02-17
     */
    public function getParticipantsData($request)
    {
        // $data = Teachers::select('user_id as value','name','major_subject')->where('deleted',0)->groupBy('user_id')->get()->toArray();
        // if(empty($data)){
        //     return [];
        // }
        // $datas = [];
        // $res = [];
        // foreach($data as $k=>&$v){
        //     $v['subject'] = $v['major_subject_array'][0]['selectValue'];
        //     unset($data[$k]['major_subject_array'],$data[$k]['major_subject']);
        // }

        // foreach($data as $k=>$v){
        //     $datas[$v['subject']][] = $v;
        // }

        // foreach($datas as $k=>$v){
        //     $res[$k]['name'] = $k;
        //     $res[$k]['value'] = $k;
        //     $res[$k]['children'] = $v;
        // }
        // return array_values($res);




        $group = Group::select('id', 'group_id','group_name as value', 'group_name as name', 'parent_id')
                ->whereIn('group_flag', [0, 1])
                ->where('deleted', 0)
                //->where('parent_id','!=',0)
                ->with(['users'=>function($q){
                    $q->where('deleted',0)->where('disabled',0)->where('username','like','%\_%')->select('id as value','group_id','nickname as name','username');
                }])
                ->get()
                ->toArray();

        $result = $this->dealGroupUserTree($group);

//        $a = $result[0]['children'];

    // dd(collect($a)->sortBy('group_id')->values()->all());

        $result = !empty($result) ? collect($result[0]['children'])->sortBy('group_id')->values()->all() : [];
        //dd($result);
        return $result;
    }

    /**
     * @Description: 处理组织结构数据
     * @Author: kzj
     * @datetime: 2023-06-12
     */
    public function dealGroupUserTree($group, $pid = 0)
    {
        // dd($group);
        $result = [];
        foreach($group as $g){

            if($g['parent_id'] == $pid){
                $children = $this->dealGroupUserTree($group, $g['group_id']);
                // dd($g, $children);
                if(empty($children)) {
                    if(!empty($g['users'])) {
                        $g['children'] = $g['users'];
                    } else {
                        continue;
                    }

                    unset($g['users']);
                } else {
                    if(empty($g['users'])) {
                        $g['children'] = $children;
                    } else {
                        $g['children'] = array_merge($children, $g['users']);
                    }

                    unset($g['users']);
                }

                $result[] = $g;

            }
        }

        return $result;
    }

    /**
     * 添加编辑数据
     * @author lxy
     * @datetime 2023-02-17
     */
    public function addAwards($request)
    {
        $id = !empty($request['id'])?$request['id']:0;
        $form_instance_id = !empty($request['form_instance_id'])?$request['form_instance_id']:0;
        $user_id = auth()->user()->id;
        $item = [];
        if(!empty($request['grade'])) array_push($item,$request['grade']);
        if(!empty($request['category'])) array_push($item,$request['category']);
        if(!empty($request['level'])) array_push($item,$request['level']);

        //学期名称
        $data_versions = Term::where('id',$request['data_version_id'])->first()->toArray();

        if($item){
            //获取旧字典
            $items = DictionaryItem::getDictionaryItem($item);
            $items = array_column($items,null,'optionId');
            if(!empty($request['grade'])) $request['grade'] = json_encode([$items[$request['grade']]]);
            if(!empty($request['category'])) $request['category'] = json_encode([$items[$request['category']]]);
            if(!empty($request['level'])) $request['level'] = json_encode([$items[$request['level']]]);
        }


        //文件
        $files = !empty($request['files'])?[$request['files']]:'';

        //参与教师
        $participant = !empty($request['participant'])?$request['participant']:'';
        $participant_id = !empty($request['participant_id'])?$request['participant_id']:'';
        $status = $request['status'] == 1?'REVIEW':'FILL_IN';
        unset($request['files'],$request['file'],$request['participant'],$request['participant_id'],$request['id'],$request['status']);
        if(empty($request['begin_date'])) unset($request['begin_date']);
        if(empty($request['end_date'])) unset($request['end_date']);

        //已经提交过的数据不能保存
        if($status == 'FILL_IN'){
            if($id){
                $fi_status = FormInstance::where('id',$form_instance_id)->value('status');
                if($fi_status != 'FILL_IN'){
                    throw new \Exception('已提交过的数据不能继续保存');
                }
            }
        }

        //dd($request);
        try{
            DB::beginTransaction();
            //文件附件
            $proof_material = [];
            $filesArr = [];
            if($files){
                $proof_material = $this->activityRepository->dealUploadFile($files);
                $filesArr = array_column(json_decode($files[0],true)?:[], 'files_id');
            }
            if(empty($filesArr)){
                throw new \Exception('请上传证明材料');
            }
            $activity   =   '';
            //添加
            if(!$id){
                //审核
                $formInstance = FormInstance::create([
                    'form_key'=>'TEACHER_AWARD_OPERATION',
                    'type'=>'ActivityCreate',
                    'owner_id'=>$user_id,
                    'status'=>$status,
                   // 'display_mode'=>$status == 'REVIEW'?'REVIEW':'EDIT',
                    'data_version_id'=>$request['data_version_id'],
                    'data_version_name'=>$data_versions['title'],
                    'creator_id'=>$user_id,
                ]);

                $request['creator_id'] = $user_id;
                $request['activity_category'] = 'TEACHER_AWARD_TABLE';
                $request['proof_material'] = $files?json_encode($proof_material):'';
                $request['form_instance_id'] = $formInstance->id;
                $activity = ActivityInfo::create(array_filter($request));
                $id = $activity->id;

            }else{  //编辑

                $formInstance = FormInstance::where('id',$form_instance_id)->first();

                if($formInstance->status == 'FILL_IN' && $status == 'REVIEW'){
                    FormInstance::where('id',$form_instance_id)->update(['status'=>$status]);
                }else if($formInstance->status == 'REVIEW_FAIL' && $status == 'REVIEW'){
                    FormInstance::where('id',$form_instance_id)->update(['status'=>$status]);
                }

                if($files){
                    $request['proof_material'] = $files?json_encode($proof_material):'';
                }
                $request['updater_id'] = $user_id;

                FormInstance::where('id',$form_instance_id)->update(['data_version_id'=>$request['data_version_id'],'data_version_name'=>$data_versions['title']]);
                ActivityInfo::where('id',$id)->update(array_filter($request));

            }
            //关联推优文件处理
            $activity = $activity?:ActivityInfo::find($id);
            $activity->files_id = $filesArr;

            //添加待办事项
            if($status=='REVIEW'){
                 //处理有驳回的数据
                 Tasks::where('form_key','TEACHER_AWARD_OPERATION')->where('form_id',$id)->where('status',1)->where('type',3)->update(['status'=>2]);
                if(!Tasks::where('form_key','TEACHER_AWARD_OPERATION')->where('form_id',$id)->where('status',1)->first()){
                    Tasks::create([
                        'name'=>'【'.$data_versions['title'].'】获奖情况-获奖情况审核',
                        'data_version_id'=>$request['data_version_id'],
                        'form_id'=>$id,
                        'form_key'=>'TEACHER_AWARD_OPERATION',
                        'start_date'=>date('Y-m-d H:i:s'),
                        'end_date'=>date('Y-m-d H:i:s'),
                        'creator_id'=>$user_id,
                        'creator_name'=>auth()->user()->nickname,
                        'param'=>'?id='.$id,
                        'url'=>'/awards/wards/check',
                        'menu_id'=>178
                    ]);
                }
            }

           //参与人员
           if($participant){
                EventStatistics::updateOrCreate(
                    ['activity_info_id' => $id],
                    [
                    'type' => '获奖情况',
                    'child_type' => !empty($request['category'])?json_decode($request['category'],true)[0]['selectValue']:'',
                    'name' => !empty($request['name'])?$request['name']:'',
                    'level' => !empty($request['level'])?json_decode($request['level'],true)[0]['selectValue']:'',
                    'participant' => $participant,
                    'date' => date('Y-m-d'),
                    'data_version_id' => $request['data_version_id'],
                ]);

                $data = [];
                Participant::where('activity_info_id',$id)->delete();
                foreach($participant_id as $k=>$v){
                    $data[$k]['created_at'] = date('Y-m-d H:i:s');
                    $data[$k]['creator_id'] = $user_id;
                    $data[$k]['updated_at'] = date('Y-m-d H:i:s');
                    $data[$k]['updater_id'] = $user_id;
                    $data[$k]['activity_info_id'] = $id;
                    if(empty($request['activity_category'])) {
                        $data[$k]['activity_category'] = 'TEACHER_AWARD_TABLE';
                    }else{
                        $data[$k]['activity_category'] = $request['activity_category'];
                    }
                    $data[$k]['user_id'] = $v;
                    $data[$k]['participant_type'] = 'PARTICIPANT';
                    $data[$k]['name'] = !empty($request['name'])?$request['name']:'';
                }
                Participant::insert($data);
            }

            DB::commit();
            return $id;

        }catch(\Exception $e){
            DB::rollback();
            throw new \Exception($e->getMessage());
        }


    }


    public function addHonor($request)
    {
        $categoryArray = [1 => '学术', 2=>'体育', 3=> '艺术', 4=> '其他'];
        $id = !empty($request['id'])?$request['id']:0;
        $form_instance_id = !empty($request['form_instance_id'])?$request['form_instance_id']:0;
        $user_id = auth()->user()->id;
        $item = [];
        if(!empty($request['grade'])) array_push($item,$request['grade']);
        if(!empty($request['class_item'])) array_push($item,$request['class_item']);
        //if(!empty($request['category'])) array_push($item,$request['category']);
        if(!empty($request['level'])) array_push($item,$request['level']);

        //学期名称
        $data_versions = Term::where('id',$request['data_version_id'])->first()->toArray();
        //var_dump($item);
        if($item){
            //获取旧字典

            $items = DictionaryItem::getDictionaryItem($item);

            $items = array_column($items,null,'optionId');
            if(!empty($request['grade'])) $request['grade'] = json_encode([$items[$request['grade']]]);
            if(!empty($request['level'])) $request['level'] = json_encode([$items[$request['level']]]);
            if(!empty($request['class_item'])) $request['class_item'] = json_encode([$items[$request['class_item']]]);
        }
        //文件
        $files = !empty($request['files'])?[$request['files']]:'';

        //参与教师
        $participant = !empty($request['participant'])?$request['participant']:'';
        $participant_id = !empty($request['participant_id'])?$request['participant_id']:'';
        $status = $request['status'] == 1?'REVIEW':'FILL_IN';
        unset($request['files'],$request['file'],$request['participant'],$request['participant_id'],$request['id'],$request['status']);
        if(empty($request['begin_date'])) unset($request['begin_date']);
        if(empty($request['end_date'])) unset($request['end_date']);
        //已经提交过的数据不能保存
        if($status == 'FILL_IN'){
            if($id){
                $fi_status = FormInstance::where('id',$form_instance_id)->value('status');
                if($fi_status != 'FILL_IN'){
                    throw new \Exception('已提交过的数据不能继续保存');
                }
            }
        }

        //dd($request);
        try{
            DB::beginTransaction();

            //文件附件
            $proof_material = [];
            $filesArr = [];
            if($files){
                $proof_material = $this->activityRepository->dealUploadFile($files);
                $filesArr = array_column(json_decode($files[0],true)?:[], 'files_id');
            }
            //添加
            if(!$id){
                //审核
                $formInstance = FormInstance::create([
                    'form_key'=>'TEACHER_HONOR_TABLE',
                    'type'=>'ActivityCreate',
                    'owner_id'=>$user_id,
                    'status'=>$status,
                    // 'display_mode'=>$status == 'REVIEW'?'REVIEW':'EDIT',
                    'data_version_id'=>$request['data_version_id'],
                    'data_version_name'=>$data_versions['title'],
                    'creator_id'=>$user_id,
                ]);

                $request['creator_id'] = $user_id;
                if(empty($request['activity_category'])) {
                    $request['activity_category'] = 'TEACHER_HONOR_TABLE';
                }
                $request['proof_material'] = $files?json_encode($proof_material):'';
                $request['form_instance_id'] = $formInstance->id;
                $activity = ActivityInfo::create(array_filter($request));
                $id = $activity->id;

            }else{  //编辑

                $formInstance = FormInstance::where('id',$form_instance_id)->first();

                if($formInstance->status == 'FILL_IN' && $status == 'REVIEW'){
                    FormInstance::where('id',$form_instance_id)->update(['status'=>$status]);
                }else if($formInstance->status == 'REVIEW_FAIL' && $status == 'REVIEW'){
                    FormInstance::where('id',$form_instance_id)->update(['status'=>$status]);
                }

                if($files){
                    $request['proof_material'] = $files?json_encode($proof_material):'';
                }
                $request['updater_id'] = $user_id;

                FormInstance::where('id',$form_instance_id)->update(['data_version_id'=>$request['data_version_id'],'data_version_name'=>$data_versions['title']]);
                ActivityInfo::where('id',$id)->update(array_filter($request));

            }
            $activity = !empty($activity)?$activity:ActivityInfo::find($id);
            $activity->files()->saveMany(Files::query()->whereIn('id', $filesArr)->get());
            $activity->files_id = $filesArr;
            //添加待办事项
            if($status=='REVIEW'){
                //处理有驳回的数据
                Tasks::where('form_key','TEACHER_HONOR_TABLE')->where('form_id',$id)->where('status',1)->where('type',3)->update(['status'=>2]);
                if(!Tasks::where('form_key','TEACHER_HONOR_TABLE')->where('form_id',$id)->where('status',1)->first()){
                    Tasks::create([
                        'name'=>'【'.$data_versions['title'].'】班级荣誉-班级荣誉情况审核',
                        'data_version_id'=>$request['data_version_id'],
                        'form_id'=>$id,
                        'form_key'=>'TEACHER_HONOR_TABLE',
                        'start_date'=>date('Y-m-d H:i:s'),
                        'end_date'=>date('Y-m-d H:i:s'),
                        'creator_id'=>$user_id,
                        'creator_name'=>auth()->user()->nickname,
                        'param'=>'?id='.$id,
                        'url'=>'/awards/wards/check',
                        'menu_id'=>178
                    ]);
                }
            }

            //参与人员
            if($participant){
                EventStatistics::updateOrCreate(
                    ['activity_info_id' => $id],
                    [
                        'type' => '班级荣誉',
                        'child_type' => !empty($request['category'])?json_decode($request['category'],true)[0]['selectValue']:'',
                        'name' => !empty($request['name'])?$request['name']:'',
                        'level' => !empty($request['level'])?json_decode($request['level'],true)[0]['selectValue']:'',
                        'participant' => $participant,
                        'date' => date('Y-m-d'),
                        'data_version_id' => $request['data_version_id'],
                    ]);

                $data = [];
                Participant::where('activity_info_id',$id)->delete();
                foreach($participant_id as $k=>$v){
                    $data[$k]['created_at'] = date('Y-m-d H:i:s');
                    $data[$k]['creator_id'] = $user_id;
                    $data[$k]['updated_at'] = date('Y-m-d H:i:s');
                    $data[$k]['updater_id'] = $user_id;
                    $data[$k]['activity_info_id'] = $id;
                    if(empty($request['activity_category'])) {
                        $data[$k]['activity_category'] = 'TEACHER_AWARD_TABLE';
                    }else{
                        $data[$k]['activity_category'] = $request['activity_category'];
                    }
                    $data[$k]['user_id'] = $v;
                    $data[$k]['participant_type'] = 'PARTICIPANT';
                    $data[$k]['name'] = !empty($request['name'])?$request['name']:'';
                }
                Participant::insert($data);
            }

            DB::commit();
            return $id;

        }catch(\Exception $e){
            DB::rollback();
            throw new \Exception($e->getMessage());
        }


    }
    /**
     * 获取一条编辑数据
     * @author lxy
     * @datetime 2023-02-23
     */
    public function getAwardsFirst($request)
    {
        $id = $request['id'];
        $result = ActivityInfo::where('id',$id)->with(['forminstance','participants','partNames'])->first();
        if(!$result){
            return [];
        }
        $result = $result->toArray();

        $data = [];
        foreach($result['participants'] as $k=>$v){
            $data[$v['participant_type']][] = $v;
        }
        $result['participants'] = !empty($data['PARTICIPANT'])?array_column($data['PARTICIPANT'],'user_id'):[];
        $result['compere'] = !empty($data['COMPERE'])?array_column($data['COMPERE'],'user_id'):[];
        //dd($result);
        $result['nickname'] = User::where('id',$result['creator_id'])->value('nickname');
       // $result['proof_material_file'] = !empty($result['proof_material_array'])? File::where('id',$result['proof_material_array'][0]['id'])->first():[];
        if(!empty($result['forminstance']['updater_id'])){
            $result['check_name'] = User::where('id',$result['forminstance']['updater_id'])->value('nickname');
        }else{
            $result['check_name'] = $result['nickname'];
        }
        return $result;
    }

    /**
     * 审核
     * @author lxy
     * @datetime 2023-02-24
     */
    public function checkAwards($request)
    {
        if(empty($request['status'])) {
            throw new \Exception('必须勾选审核结果！');
        }
        $result = FormInstance::where('id',$request['form_instance_id'])->update([
            'status'=>$request['status'],
            'comment'=>$request['comment'],
            'updater_id'=>auth()->user()->id,
        ]);

        //修改待办事项
        Tasks::where('form_key','TEACHER_AWARD_OPERATION')->where('form_id',$request['id'])->update(['status'=>2]);

        //如果是驳回，重新给申报人发起待办事项
        if($request['status']== 'REVIEW_FAIL'){
            $task = Tasks::where('form_key','TEACHER_AWARD_OPERATION')->where('form_id',$request['id'])->where('type',1)->orderBy('created_at','desc')->first();
            if(!$task){
                return [];
            }
            $task = $task->toArray();
            Tasks::create([
                'name'=>$task['name'].'驳回',
                'type' => 3,
                'data_version_id'=>$task['data_version_id'],
                'form_id'=>$task['form_id'],
                'form_key'=>'TEACHER_AWARD_OPERATION',
                'start_date'=>date('Y-m-d H:i:s'),
                'end_date'=>date('Y-m-d H:i:s'),
                'c_user_id' => $task['creator_id'],
                'c_user_name' => $task['creator_name'],
                'creator_id'=>auth()->user()->id,
                'creator_name'=>auth()->user()->nickname,
                'param'=>$task['param'],
                'url'=>'/awards/wards/add',
                'menu_id'=>177
            ]);
        }

        return $result;
    }

    /**
     * 删除
     * @author lxy
     * @datetime 2023-02-24
     */
    public function delAwards($request)
    {
        $id = $request['id'];
        Tasks::where('form_key','TEACHER_AWARD_OPERATION')->where('form_id',$id)->where('status',1)->delete();
        return ActivityInfo::where('id',$id)->update(['deleted'=>1]);
    }


    /**
     * 删除
     * @author lxy
     * @datetime 2023-02-24
     */
    public function pushAwards($request)
    {
        $id = $request['id'];
        $activityInfo = ActivityInfo::query()->where(['id' => $id])->firstOrFail();
        $activityInfo->is_push  = $activityInfo->is_push ? 0 : 1;

        return $activityInfo->save();
    }

    /*
         * @Description: 任教学科导入
         * @Author:  qiankun
         * @Date: 2025-06-05 09:40:16
         */
    public function importHonor($request)
    {
        ini_set('memory_limit', '1280M');
        ini_set('max_execution_time', '0');
        $data = Excel::toArray(new ExcelImport(), request()->file('file'));

        $data = $data[0];
        if (count($data) < 2) {
            //throw new \Exception('模板不能为空');
        }

        $user = Auth::user();
        $errCount = 0;
        $teachingSubjects = [];
        $now = now();
        $terms = Term::where('deleted', 0)->get();
        $dictionaryItems = DictionaryItem::select('code', 'item_order as order','id as optionId','parent_id as parentId','item_value as selectKey','item_name as selectValue')
            ->whereIn('code', ['CLASS', 'LEVEL', 'GRADE','award_grade'])
            ->get();

        foreach ($data as $k => &$v) {
            if ($k > 0) {
                //$v[0].学年学期 $v[1]奖项名称 $v[2]颁奖日期 $v[3]年级 $v[4]班级 $v[5]奖项名次 $v[6]级别
                if(!$v[0] || !$v[1] || !$v[3] || !$v[4] || !$v[5] || !$v[6]) {
                    array_push($v, '请完善该行数据或删除这一行空数据再操作！');
                    $errCount++;
                    continue;
                }

                $term = $terms->where('title', $v[0])->first();
                if (!$term) {
                    array_push($v, '该学期不存在，请检查学期【'.$v[0].'】！');
                    $errCount++;
                    continue;
                }
                $ts['data_version_id'] = $term->id;
                $ts['data_version_name'] = $term->title;
                $ts['begin_date'] = excelDateFormat($v[2], 'Y-m-d');
                $ts['name'] = $v[1];
                $gradeDicInfo = $dictionaryItems->where('code', 'GRADE')->where('selectValue', $v[3])->first();
                if (!$gradeDicInfo) {
                    array_push($v, '该任教年级不存在，请检查任教年级【'.$v[3].'】！');
                    $errCount++;
                    continue;
                } else {
                    $ts['grade'] = json_encode([$gradeDicInfo->toArray()]);
                }

                $classDicInfo = DictionaryItem::select('code', 'item_order as order','id as optionId','parent_id as parentId','item_value as selectKey','item_name as selectValue')
                    ->where('code', 'CLASS')->where('item_name',$v[4])->first();
                if (!$classDicInfo) {
                    array_push($v, '该任教班级不存在，请检查任教班级【'.$v[4].'】！');
                    $errCount++;
                    continue;
                } else {
                    $ts['class_item'] = json_encode([$classDicInfo->toArray()]);
                }

                $levelDicInfo = DictionaryItem::select('code', 'item_order as order','id as optionId','parent_id as parentId','item_value as selectKey','item_name as selectValue')
                    ->where('code', 'LEVEL')->where('item_name',$v[6])->first();
                if (!$levelDicInfo) {
                    array_push($v, '该级别不存在，请检查级别【'.$v[6].'】！');
                    $errCount++;
                    continue;
                } else {
                    $ts['level'] = json_encode([$levelDicInfo->toArray()]);
                }
                $awardDicInfo = DictionaryItem::select('code', 'item_order as order','id as optionId','parent_id as parentId','item_value as selectKey','item_name as selectValue')
                    ->where('code', 'award_grade')->where('item_name',$v[5])->first();
                if (!$awardDicInfo) {
                    array_push($v, '名次不存在，请检查名次【'.$v[5].'】！');
                    $errCount++;
                    continue;
                } else {
                    $ts['customer_grade'] = $awardDicInfo->optionId;
                }
                $ts['activity_category'] = 'TEACHER_HONOR_TABLE';
                $ts['creator_id'] = $user->id;
                $teachingSubjects[] = $ts;
            } else {
                if(
                    !(isset($v[0]) && trim($v[0]) == '学年学期') ||
                    !(isset($v[1]) && trim($v[1]) == '奖项名称') ||
                    !(isset($v[2]) && trim($v[2]) == '颁奖日期') ||
                    !(isset($v[3]) && trim($v[3]) == '年级') ||
                    !(isset($v[4]) && trim($v[4]) == '班级') ||
                    !(isset($v[5]) && trim($v[5]) == '奖项名次') ||
                    !(isset($v[6]) && trim($v[6]) == '级别')
                ) {
                    throw new \Exception('模板错误，请上传正确的模板！');
                }

                array_push($v, '错误提示');
            }
        }

        $result = [
            'is_fail' => 1, //1-成功 0-失败
            'msg' => '导入成功',
            'file_name' => ''
        ];
        if ($errCount == 0) {
            DB::beginTransaction();
            try {
                //var_dump($teachingSubjects);exit();
                foreach($teachingSubjects as &$teachingSubject) {
                    $formInstance = FormInstance::create([
                        'data_version_id' => $teachingSubject['data_version_id'],
                        'data_version_name' => $teachingSubject['data_version_name'],
                        'form_key'=> 'TEACHER_HONOR_TABLE',
                        'type' => 'ActivityImport',
                        'owner_id' => $user->id,
                        'status' => 'PASS',
                        'creator_id' => $user->id,
                    ]);


                    $teachingSubject['form_instance_id'] = $formInstance->id;
                    //unset($teachingSubject['data_version_name']);
                }

                //批量插入导入数据
                //TeachingSubject::insert($teachingSubjects);
                ActivityInfo::insert($teachingSubjects);
                DB::commit();
            } catch (\Exception $exception) {
                DB::rollback();
                Log::error($exception->getMessage());
                throw new \Exception($exception->getMessage());
            }

            return $result;
        } else {
            //保存错误文件
            $file_name = md5(auth()->user()->id . time()) . '.xlsx';
            Excel::store(new ExcelExport(array_values($data)), $file_name, 'excel');

            $result['is_fail'] = 0;
            $result['msg'] = '导入失败';
            $result['file_name'] = '/download/excel/' . $file_name;
            return $result;
        }
    }
}

?>
